#include <allegro5\allegro.h>
#include <allegro5\allegro_font.h>
#include <allegro5\allegro_ttf.h>
#include <allegro5\allegro_native_dialog.h>
#include <allegro5\allegro_primitives.h>
#include <allegro5\allegro_image.h>
#include <allegro5\allegro_audio.h>
#include <allegro5\allegro_acodec.h>
#include <iostream>
#include "sw_input_manager.h"
#include "sw_game_state_master.h"
#include "globals.h"

#include "sw_game_manager.h"
using namespace std;

sw_game_manager::sw_game_manager() {
}

sw_game_manager::~sw_game_manager() {
}

int sw_game_manager::play_game() {
	bool done = false;
	int frame_count = 0; // TODO this variable is useless
	bool redraw = true;

	// allegro variables
	ALLEGRO_TIMER* timer = al_create_timer(1.0 / global_frames_per_second);
	ALLEGRO_EVENT_QUEUE* event_queue = al_create_event_queue();
	
	al_register_event_source(event_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_display_event_source(global_screen_display));
	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	al_register_event_source(event_queue, al_get_mouse_event_source());

	global_game_state->draw_on_screen();

	al_start_timer(timer);

	while(!done) {
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		switch(ev.type) {
		case ALLEGRO_EVENT_KEY_DOWN:
			global_input_manager->key_down(ev.keyboard.keycode);
			break;
		case ALLEGRO_EVENT_KEY_UP:
			if (ev.keyboard.keycode==ALLEGRO_KEY_ESCAPE) {
				done = true;
			}
			global_input_manager->key_up(ev.keyboard.keycode);
			break;
		case ALLEGRO_EVENT_DISPLAY_CLOSE:
			done = true;
			break;
		case ALLEGRO_EVENT_TIMER:
			redraw = true;
			break;
		case ALLEGRO_EVENT_MOUSE_AXES:
			global_input_manager->mouse_moved(ev.mouse.x, ev.mouse.y);
			break;
		}

		if (redraw && al_is_event_queue_empty(event_queue)) {
			redraw = false;
		
			frame_count ++;

			global_game_state->compute_timestep();
			global_game_state->draw_on_screen();

			global_input_manager->reset_counts();
		}
	}

	al_destroy_display(global_screen_display);

	return 0;
}